# -*- coding:utf-8 -*-
import Pluto,struct,codecs,fnmatch,re

def makestr(i):
        string=[]
        j=0
        while j>=0:
                if re.match(u'－'*18,lines[i+2+j]):
                        break
                string.append(lines[i+2+j])
                j+=1
        return ''.join(string)[:-2]

def importer(baseoffset):
        fp=codecs.open(fn,'rb','utf16')
        global lines
        lines=fp.readlines()
        fp.close()
        line_num=len(lines)
        
        text_list=[]
        for i in xrange(line_num):
                if re.match('No.\d+',lines[i]):
                        text=makestr(i)
                        text_list.append(text)
        
        tar=open(fn[:-13],'r+b')
        tar.seek(baseoffset+0x20)
        num=struct.unpack('i',tar.read(4))[0]
        if len(text_list)!=num:
                print 'The number is wrong!'
        
        tar.seek(baseoffset+0x28)
        firstoffset=struct.unpack('i',tar.read(4))[0]+16+baseoffset
        tar.seek(firstoffset)

        offsetlist=[]
        for text in text_list:
                offsetlist.append(tar.tell()-16-baseoffset)
                text=text.replace('\r','')
                tar.write(text.encode('utf16')[2:])
                tar.write('\x00\x00')
        
        for j in xrange(num):
                tar.seek(baseoffset+0x24+j*8+4)
                tar.write(struct.pack('i',offsetlist[j]))
        tar.close()

fl=Pluto.walk('resources2')
for fn in fl:
        if not fnmatch.fnmatch(fn,'*.txt'):
                continue
        print fn
        baseoffset=int(fn[-12:-4],16)
        importer(baseoffset)